import { defineStore } from 'pinia'
import { getCartList } from '@/api/cart'

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: [],
    cartCount: 0,
    stats: null
  }),
  
  getters: {
    // 选中的商品
    selectedItems: (state) => {
      return state.cartList.filter(item => item.is_selected === 1)
    },
    
    // 选中商品的总价
    totalPrice: (state) => {
      return state.cartList
        .filter(item => item.is_selected === 1)
        .reduce((total, item) => {
          return total + parseFloat(item.product_price) * item.quantity
        }, 0)
        .toFixed(2)
    },
    
    // 是否全选
    isAllSelected: (state) => {
      if (!Array.isArray(state.cartList) || state.cartList.length === 0) return false
      return state.cartList.every(item => item.is_selected === 1)
    }
  },
  
  actions: {
    // 获取购物车列表
    async fetchCartList() {
      try {
        const res = await getCartList()
        // 修复：使用 res.data.items 而不是 res.data
        this.cartList = res.data.items || []
        this.stats = res.data.stats || null
        this.cartCount = this.cartList.length
      } catch (error) {
        console.error('获取购物车列表失败：', error)
        // 确保出错时 cartList 也是数组
        this.cartList = []
        this.cartCount = 0
      }
    },
    
    // 更新购物车数量
    updateCartCount() {
      this.cartCount = this.cartList.length
    }
  }
})
